package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.common.GiteeUtils;
import com.bw.common.JwtUtils;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
public class GiteeLoginController {

    @Autowired
    UserMapper userMapper;


    /**
     * 用来接收gitee发送过来的临时授权码
     *
     * @param code
     * @return
     */
    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletResponse response, Model model) {
        System.out.println("接收到的临时授权码" + code);
        //根据临时授权码 获取token
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " + tokenByCode);

        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);

        System.out.println("获取到的用户资源 " + JSON.toJSONString(userInfoByToken));

        // 找出一些有用字段  存到自己系统的数据库，执行注册

        String name = userInfoByToken.getString("login"); // 个人空间地址  把个人空间地址当做新注册用户的用户名
        String nickName = userInfoByToken.getString("name"); // 昵称
        String avatarUrl = userInfoByToken.getString("avatar_url"); // 头像
        Integer giteeId = userInfoByToken.getInteger("id"); // gitee系统的主键id



        // 之前是否已经注册过
        User userFromDB = userMapper.selectByName(name);
        if (userFromDB == null){  //之前没有注册过  执行注册
            userFromDB = new User();
            userFromDB.setName(name);
            userFromDB.setNickName(nickName);
            userFromDB.setGiteeId(giteeId);
            userFromDB.setAvatarUrl(avatarUrl);
            userMapper.addUser(userFromDB);
        }else { // 如果之前已经注册过， 刷新一下这个用户的昵称和头像
            userFromDB.setNickName(nickName);
            userFromDB.setAvatarUrl(avatarUrl);
            userMapper.updateUser(userFromDB);

        }
        // 加密用户信息  得到token
        String token = JwtUtils.createToken(userFromDB);
        Cookie cookie = new Cookie("token", token);
        response.addCookie(cookie);
        model.addAttribute("nickName",nickName);
        model.addAttribute("avatarUrl",avatarUrl);
        return "list";
    }
}
